/*
MoniBabyTor - a webcam based monitoring app for babies
    Copyright (C) 2013 Assaf Paz

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "mjpegfile.h"
#include <QImage>
#include <QDebug>

MJpegFile::MJpegFile(QObject *parent) :
    QObject(parent), m_videoDevice(NULL)
{
}

void MJpegFile::setVideoDevice(QIODevice *videoDevice)
{
    if (m_videoDevice != NULL)
    {
        disconnect(m_videoDevice, SIGNAL(readyRead()), this, SLOT(imageDataReady()));
    }

    m_videoDevice = videoDevice;
    if (m_videoDevice != NULL)
    {
        connect(m_videoDevice, SIGNAL(readyRead()), this, SLOT(imageDataReady()));
    }
}

void MJpegFile::imageDataReady()
{
    static const int ContentLengthKeyLength = strlen("Content-length: ");

    QByteArray filler = m_videoDevice->readLine(1000);
    while (filler.startsWith("--video boundary--") || filler.startsWith("\r\n"))
    {
        filler = m_videoDevice->readLine(1000);
    }
    QByteArray contentLengthByteArray = filler;
    int contentLength = contentLengthByteArray.remove(0, ContentLengthKeyLength).trimmed().toInt();
    QByteArray date = m_videoDevice->readLine(1000);
    QByteArray contentType = m_videoDevice->readLine(1000);
    QByteArray imageData = m_videoDevice->read(contentLength);
    if (imageData.startsWith("\r\n"))
    {
        imageData.remove(0, 2);
        imageData.append(m_videoDevice->read(2));
    }

    if (imageData.length() > 0 && imageData.length() == contentLength)
    {
        QImage* image = new QImage(QImage::fromData(imageData));
        if (image->isNull() == false)
        {
            emit imageReceived(image);
        }
    }
}
